const { BaseController } = require('../Base')
const crypto = require('crypto')

class CryptoMenu extends BaseController {
  // 创建哈希加密
  createCrypto(ctx) {
    let { content, type } = ctx.request.body
    if (!content) {
      return (ctx.body = this.resError('请输入加密内容!'))
    }
    if (!type) {
      return (ctx.body = this.resError('请选择加密类型!'))
    }
    let result = crypto.createHash(type).update(content).digest('hex')
    ctx.body = this.resSuccess(result)
  }
  // aes加解密 key,iv,data type 1加密 2解密
  aesCrypto(ctx) {
    let { key, iv, content, type } = ctx.request.body
    if (!key) {
      return (ctx.body = this.resError('请输入密匙key且长度为16!'))
    }
    if (!iv) {
      return (ctx.body = this.resError('请输入偏移iv且长度为16!'))
    }
    if (!content) {
      return (ctx.body = this.resError('请输入内容!'))
    }
    if (!type) {
      return (ctx.body = this.resError('请选择加密或解密类型type 1 2!'))
    }
    if (type == 1) {
      ctx.body = this.resSuccess(this.tools.crypto.aesEncrypt(key, iv, content))
    } else if (type == 2) {
      ctx.body = this.resSuccess(this.tools.crypto.aesDecrypt(key, iv, content))
    } else {
      ctx.body = this.resError('类型错误!')
    }
  }
}

const ex = new CryptoMenu()
module.exports = ex
